package nju.software.xkxt.service.implement;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import nju.software.xkxt.data.dao.CourseDao;
import nju.software.xkxt.data.dao.SelectionDao;
import nju.software.xkxt.data.dataobject.SelectionDO;
import nju.software.xkxt.service.SelectionService;
import nju.software.xkxt.service.model.SelectionModel;

public class SelectionServiceImpl implements SelectionService {

	SelectionDao selectionDao;
	CourseDao courseDao;

	public List<SelectionModel> getSelectionModelByUserId(int userId) {
		List<SelectionDO> selectionDOs = selectionDao
				.getSelectionDOByUserId(userId);
		List<SelectionModel> selectionModels = new ArrayList<SelectionModel>();
		for (SelectionDO selectionDO : selectionDOs) {
			String courseName = courseDao.getCourseById(
					selectionDO.getCourseId()).getCName();
			Long num = selectionDao.getNumByCourseId(selectionDO.getCourseId());
			SelectionModel selectionModel = new SelectionModel(selectionDO,
					courseName, num);
			selectionModels.add(selectionModel);
		}
		return selectionModels;
	}

	public List<SelectionModel> getSelection() {
		List<SelectionDO> selectionDOs = selectionDao.getSelection();
		List<SelectionModel> selectionModels = new ArrayList<SelectionModel>();
		for (SelectionDO selectionDO : selectionDOs) {
			String courseName = courseDao.getCourseById(
					selectionDO.getCourseId()).getCName();
			Long num = selectionDao.getNumByCourseId(selectionDO.getCourseId());
			SelectionModel selectionModel = new SelectionModel(selectionDO,
					courseName, num);
			selectionModels.add(selectionModel);
		}
		return selectionModels;
	}

	public boolean updateSelectionModelByUserId(int userId,
			Map<Integer, Integer> selection) {
		Iterator<Integer> iter = selection.keySet().iterator();
		while (iter.hasNext()) {
			Integer key = iter.next();
			Integer val = selection.get(key);
			if (!selectionDao.updateEntryByCidAndUid(key, userId, val))
				return false;
		}
		return true;
	}

	public boolean delete(int courseId) {
		boolean b = selectionDao.delete(courseId);
		return b;
	}

	public void setSelectionDao(SelectionDao selectionDao) {
		this.selectionDao = selectionDao;
	}

	public void setCourseDao(CourseDao courseDao) {
		this.courseDao = courseDao;
	}

}
